//
//  SelectQuestionGroupViewController.swift
//  RabbleWabble
//
//  Created by TRS-Mobile on 2021/9/8.
//

import UIKit

class SelectQuestionGroupViewController: UIViewController {

    let appSettings = AppSettings.shared
    
    @IBOutlet var tableView: UITableView! {
        didSet {
            tableView.tableFooterView = UIView()
        }
    }
    
//    let questionGroups = QuestionGroup.allGroups()
    private let questionGroupCaretaker = QuestionGroupCaretaker()
    private var questionGroups: [QuestionGroup] {
        return questionGroupCaretaker.questionGroups
    }
    private var selectedQestionGroup: QuestionGroup! {
        get {
            return questionGroupCaretaker.selectedQuestionGroup
        }
        set {
            questionGroupCaretaker.selectedQuestionGroup = newValue
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        questionGroups.forEach {
            print("\($0.title): " +
                "correctCount \($0.score.correctCount), " +
                    "incorrectCount \($0.score.incorrectCount)")
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
//        guard let vc = segue.destination as? QuestionViewController else { return }

        if let vc = segue.destination as? QuestionViewController {
            //        vc.questionGroup = selectedQestionGroup
            //        vc.questionStrategy = RandomQuestionStrategy(questionGroup: selectedQestionGroup)
            //        vc.questionStrategy = appSettings.questionStrategy(for: selectedQestionGroup)
            vc.questionStrategy = appSettings.questionStrategy(forQuestion: questionGroupCaretaker)
            vc.delegate = self
        } else if let nVc = segue.destination as? UINavigationController, let vc = nVc.topViewController as? CreateQuestionGroupViewController {
            vc.delegate = self
        }
        
    }
}

extension SelectQuestionGroupViewController: UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return questionGroups.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "QuestionGroupCell") as! QuestionGroupCell
        let questionGroup = questionGroups[indexPath.row]
        cell.titleLabel.text = questionGroup.title
        
        questionGroup.score.runningPercentage
            .addObserver(cell, removeIfExists: true, options: [.initial, .new])
            {[weak cell] (percentage, _) in
                DispatchQueue.main.async {
                    cell?.percentageLabel.text = String(format: "%.0f %%", round(100 * percentage))
                }
        }
        return cell
    }
}

extension SelectQuestionGroupViewController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        selectedQestionGroup = questionGroups[indexPath.row]
        return indexPath
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension SelectQuestionGroupViewController: QuestionViewControllerDelegate {
    
    func questionViewController(_ vc: QuestionViewController, didCancel questionStrategy: QuestionStrategy) {
        navigationController?.popViewController(animated: true)
    }
    
    func questionViewController(_ vc: QuestionViewController, didComplete questionStrategy: QuestionStrategy) {
        navigationController?.popViewController(animated: true)
    }
//    func questionViewController(_ vc: QuestionViewController, didCancel questionGroup: QuestionGroup, at questionIndex: Int) {
//        navigationController?.popViewController(animated: true)
//    }
//
//    func questionViewController(_ vc: QuestionViewController, didComplete questionGroup: QuestionGroup) {
//        navigationController?.popViewController(animated: true)
//    }
}

extension SelectQuestionGroupViewController: CreateQuestionGroupViewControllerDelegate {
    func createQuestionGroupViewControllerDidCancel(_ viewController: CreateQuestionGroupViewController) {
        dismiss(animated: true, completion: .none)
    }
    
    func createQuestionGroupViewController(_ viewController: CreateQuestionGroupViewController, created questionGroup: QuestionGroup) {
        questionGroupCaretaker.questionGroups.append(questionGroup)
        try? questionGroupCaretaker.save()
        dismiss(animated: true, completion: .none)
        tableView.reloadData()
    }
}
